/**
 * login module
 */
import { getCookie, saveCookie } from 'utils/authService'
import LoginAction from 'api/login'
import lockr from 'lockr'
import Vue from 'vue'
export const LOGIN_SUCCESS = 'LOGIN_SUCCESS'
export const USERINFO_SUCCESS = 'USERINFO_SUCCESS'
export const USERINFO_FAILURE = 'USERINFO_FAILURE'
export const LOGOUT_USER = 'LOGOUT_USER'
export const UPDATE_USER_SUCCESS = 'UPDATE_USER_SUCCESS'
export const GET_USER = 'GET_USER'
export const UPDATE_TOKEN = 'UPDATE_TOKEN'

export default {
    state: {
        user: null,
        token: getCookie('token') || null,
        msg: ''
    },
    mutations: {
        [LOGIN_SUCCESS](state, user) {
            saveCookie('token', user.token);
            state.token = user.token;
            state.user = user;
            lockr.set('user', user)
        },
        [USERINFO_SUCCESS](state, user) {
            saveCookie('token', user.token);
            state.token = user.token;
            state.user = user
            lockr.set('user', user)
        },
        [USERINFO_FAILURE](state, msg) {
            state.token = getCookie('token') || null
            state.user = null
            lockr.rm('user')
            state.msg = msg
        },
        [LOGOUT_USER](state, user) {
            state.token = getCookie('token') || null;
            state.user = null;
            lockr.rm('user');
        },
        [UPDATE_USER_SUCCESS](state, user) {
            saveCookie('token', user.token);
            state.token = user.token;
            state.user = user
            lockr.set('user', user)
        },
        [GET_USER](state) {
            let user = lockr.get('user')
            if (user) {
                state.user = user
            } else {
                state.user = null
            }
        },
        [UPDATE_TOKEN](state, token) {
            let user = lockr.get('user')
            if (user) {
                user.token = token
                state.user = user
                state.token = token
            } else {
                state.user = null
                state.token = null
            }
        }
    },
    actions: {}
}